package com.liang.xiao.sumstep;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @describe: 统计mapreduce练习
 * @author: xiaoliang.liu
 * @date: 2018/4/29 13:21  v1.0
 */
public class SumStep {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance(new Configuration());
        job.setJarByClass(SumStep.class);

        // map
        job.setMapperClass(SumMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(InfoBean.class);
        FileInputFormat.setInputPaths(job, new Path(args[0]));

        // reduce
        job.setReducerClass(SumReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(InfoBean.class);
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // 提交
        job.waitForCompletion(true);


    }

    /**
     * map
     */
    public static class SumMapper extends Mapper<LongWritable, Text, Text, InfoBean> {
        private Text k = new Text();
        InfoBean v = new InfoBean();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] fields = line.split("\t");

            String account = fields[0];
            double in = Double.parseDouble(fields[1]);
            double out = Double.parseDouble(fields[2]);

            k.set(account);
            v.set(account, in, out);

            context.write(k, v);

        }
    }

    /**
     * reduce
     */
    public static class SumReduce extends Reducer<Text, InfoBean, Text, InfoBean> {

        private InfoBean v = new InfoBean();

        @Override
        protected void reduce(Text key, Iterable<InfoBean> values, Context context) throws IOException, InterruptedException {

            double inSum = 0;
            double outSum = 0;

            for (InfoBean value : values) {
                inSum += value.getIncome();
                outSum += value.getExpense();
            }

            v.set("", inSum, outSum);

            context.write(key, v);

        }
    }
}
